package com.example.musicplayer.controller;

import com.example.musicplayer.mapper.LoveMusicMapper;
import com.example.musicplayer.mapper.MusicMapper;
import com.example.musicplayer.model.Music;
import com.example.musicplayer.model.User;
import com.example.musicplayer.tools.Constant;
import com.example.musicplayer.tools.ResponseBodyMessage;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Resource
    private MusicMapper musicMapper;
    @Resource
    private LoveMusicMapper loveMusicMapper;
    /**
     新增⾳乐
     @param singer 歌手名称
     */
    @RequestMapping(value = "/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest req,
                                                    HttpServletResponse resp) throws IOException {
        //无session就不创建
        HttpSession httpSession = req.getSession(false);
        if (httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1, "没有登录！", false);
        }
        String filenameAndType = file.getOriginalFilename();

        System.out.println("filenameAndType---->>>>>>>>>>" + filenameAndType);

        String path = SAVE_PATH + "\\ " + filenameAndType;

        File dest = new File(path);
        System.out.println("dest:=>" + dest.getPath());

        if (!dest.exists()) {
            dest.mkdirs();
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "上传失败", false);
        }
        //数据库当中存储的歌曲不包括.mp3.所以需要进行截取
        String title = filenameAndType.substring(0, filenameAndType.lastIndexOf("."));
        //SimpleDateFormat来格式化当前的系统时间
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sf.format(new Date());
        //这里会被用到 播放音乐的模块
        String url = "/CloudMusic/get?path="+title;
        User user =
                (User)httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId = user.getId();
         int ret = musicMapper.insert(title,singer,time,url,userId);
        if(ret == 1){
        }else{
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库上传失败,删除上传的⾳乐！",false);
        }
        return new ResponseBodyMessage<>(0,"上传成功！",true);
    }

//    /**
//     根据ID删除⾳乐
//     @param id
//     @return
//     */
//    @RequestMapping("/delete")
//    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
//        int musicId = Integer.parseInt(id);
//        Music music = musicMapper.findMusicById(musicId);
//        if (music == null)
//            return new ResponseBodyMessage<>(-1,"没有你所需要的音乐",false);
//            int ret = musicMapper.deleteMusicById(musicId);
//            if (ret == 1) {
//                int index = music.getUrl().lastIndexOf("=");
//                String filename = music.getUrl().substring(index + 1);
//                File file = new File(SAVE_PATH + "/" + filename + ".mp3");
//                System.out.println("路径为:" + file.getPath());
//
//                if (file.delete()) {
//                    return new ResponseBodyMessage<>(0, "删除音乐成功", true);
//                } else {
//                    return new ResponseBodyMessage<>(1, "删除音乐失败", false);
//                }
//            }else {
//                return new ResponseBodyMessage<>(-1,"在数据库中删除音乐失败",false);
//            }
//        }
//
//    /**
//     根据id数组批量删除⾳乐
//     @param id
//     @return
//     */
//    @RequestMapping("/deleteSel")
//    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]")
//                                                               List<Integer> id) {
//        int sum = 0;
//        for (int i = 0; i < id.size(); i++) {
//            Music music = musicMapper.findMusicById(id.get(i));
//            int ret = musicMapper.deleteMusicById(id.get(i));
//            if(ret == 1) {
//                //数据库删除成功，那么服务器上的数据也需要发⽣改变
//                //删除服务器⽬录下的对应的⽂件
//                int index = music.getUrl().lastIndexOf("=");
//                String filename = music.getUrl().substring(index+1);
//                File file = new File(SAVE_PATH+"\\"+filename+".mp3");
//                if(file.delete()) {
//                    sum += ret;
//                }else {
//                    System.out.println("删除失败！");
//                    return new ResponseBodyMessage<>(-1,"删除服务器上的⾳乐失败",false);
//                }
//            }else {
//                System.out.println("删除失败！");
//                return new ResponseBodyMessage<>(-1,"删除数据上的⾳乐信息失败",false);
//            }
//        }
//        if(sum == id.size()) {
//            System.out.println("删除成功！");
//            return new ResponseBodyMessage<>(0,"批量删除成功",true);
//        }else {
//            System.out.println("删除失败！");
//            return new ResponseBodyMessage<>(0,"批量删除成功",false);
//        }
//    }
        @RequestMapping("/delete")

        public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id) {
            int iid = Integer.parseInt(id);
            Music music = musicMapper.findMusicById(iid);
            if(music == null)
                return new ResponseBodyMessage<>(-1,"没有你要删除的⾳乐",false);
            int ret = musicMapper.deleteMusicById(iid);
            if(ret == 1) {
                //数据库删除成功，那么服务器上的数据也需要发⽣改变
                //删除服务器⽬录下的对应的⽂件
                int index = music.getUrl().lastIndexOf("=");
                String filename = music.getUrl().substring(index+1);
                File file = new File(SAVE_PATH+"\\"+filename+".mp3");
                System.out.println("此时的路径："+file.getPath());
                if(file.delete()) {
                    //同步删除lovemusic表中的数据
                    loveMusicMapper.deleteLoveMusicById(iid);
                    return new ResponseBodyMessage<>(0,"删除服务器⾳乐成功",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"删除服务器⾳乐失败",false);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"删除数据库中的⾳乐失败",false);
            }
        }

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]")
                                                               List<Integer> id) {
        //System.out.println(id);

        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            int musicId = id.get(i);
            Music music = musicMapper.findMusicById(musicId);
            int ret = musicMapper.deleteMusicById(musicId);
            if(ret == 1) {
                //数据库删除成功，那么服务器上的数据也需要发⽣改变
                //删除服务器⽬录下的对应的⽂件
                int index = music.getUrl().lastIndexOf("=");
                String filename = music.getUrl().substring(index+1);
                File file = new File(SAVE_PATH+"\\"+filename+".mp3");
                if(file.delete()) {
                    //同步删除lovemusic表中的数据
                    loveMusicMapper.deleteLoveMusicById(musicId);
                    sum += ret;
                }else {
                    System.out.println("删除失败！");
                    return new ResponseBodyMessage<>(-1,"删除服务器上的⾳乐失败",false);
                }
            }else {
                System.out.println("删除失败！");
                return new ResponseBodyMessage<>(-1,"删除数据上的⾳乐信息失败",false);
            }
        }
        if(sum == id.size()) {
            System.out.println("删除成功！");
            return new ResponseBodyMessage<>(0,"批量删除成功",true);
        }else {
            System.out.println("删除失败！");
            return new ResponseBodyMessage<>(0,"批量删除失败",false);
        }
    }


    /**
     根据musicName查询音乐
     @param musicName
     @return
     */
    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required=false)String musicName) {
        List<Music> musicList = null;
        if(musicName != null) {
            musicList = musicMapper.findMusicByMusicName(musicName);
        }else {
            //默认查询全部的⾳乐
            musicList = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(0,"查询到了歌曲的信息",musicList);
    }
}

